import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";
import router from "@/router/index"

axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
axios.defaults.timeout = 1000 * 10;
axios.defaults.headers["Content-Type"] = 'application/json';

const KLogin = JSON.parse(sessionStorage.getItem("KLogin"));
if (KLogin) axios.defaults.headers.common["Authorization"] = "Bearer " + KLogin.accessToken
else axios.defaults.headers.common["Authorization"] = ""

function encodeURIParams(config) {
  let url = config.url
  url += '?'
  const keys = Object.keys(config.params)
  for (const key of keys) {
    url += `${key}=${encodeURIComponent(config.params[key])}&`
  }
  url = url.substring(0, url.length - 1)
  config.params = {}
  return url
}

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  if (config.method === 'get' && config.params) {
    config.url = encodeURIParams(config)
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    if (response.data.code === 401) {
      router.push("/login")
      ElMessage.error("账号未登录或已过期");
    } else if (response.data.code !== 0 && response.config.responseType !== "blob") {
      ElMessage.error(response.data.msg);
      return Promise.reject(response);
    }
    return response;
  },
  function (error) {
    // ElMessage.error(error.message);
    ElMessage.error("请求服务器失败，请稍后重试");
    return Promise.reject(error);
  }
);

export default axios;
